import com.google.common.io.Files
import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.nio.charset.StandardCharsets;
import groovy.json.StringEscapeUtils;
import java.lang.String;

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.sample"
typeMapping = [
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|real/)        : "Double",
        (~/(?i)bit/)                      : "Boolean",
        (~/(?i)decimal/)                  : "BigDecimal",
        (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
        (~/(?i)date/)                     : "java.sql.Date",
        (~/(?i)time/)                     : "java.sql.Time",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    //自动查找命名空间
    packageName = findPackageName(dir)
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table.getName()) }
}

def generate(out, className, fields, tableName) {
    if(packageName != "") out.println "package $packageName;"
    out.println ""
    out.println "import com.fasterxml.jackson.annotation.JsonFormat;"
    out.println "import lombok.Data;"
    out.println "import lombok.EqualsAndHashCode;"
    out.println "import lombok.NoArgsConstructor;"
    out.println "import lombok.ToString;"
    out.println "import lombok.experimental.Accessors;"
    out.println "import com.ruoyi.common.annotation.Excel;"
    out.println "import com.baomidou.mybatisplus.annotation.TableId;"
    out.println "import com.baomidou.mybatisplus.annotation.TableName;"
    out.println "import com.baomidou.mybatisplus.annotation.IdType;"
    out.println "import java.io.Serializable;"
    out.println "import java.util.Date;"
    out.println "import java.math.BigDecimal;"
    out.println ""
    out.println "@Data"
    out.println "@ToString"
    out.println "@EqualsAndHashCode"
    out.println "@NoArgsConstructor"
    out.println "@Accessors(chain = true)"
    out.println "@TableName(\"${tableName}\")"
    out.println "public class $className {"
    fields.each() {
        def auto = it.isAuto ? ", type = IdType.AUTO" : "";
        if(it.comment != "") out.println("  /** ${it.comment} */")
        if(DasUtil.isPrimary(it.column)) out.println "  @TableId(value = \"${it.columnName}\"${auto})"
        if (it.annos != "") out.println "  ${it.annos}"
        if(it.type == "java.sql.Timestamp") out.println("  @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")")
        if(it.type == "java.sql.Timestamp") out.println("  @Excel(name = \"${it.comment}\" , width = 30, dateFormat = \"yyyy-MM-dd\")")
        if(it.type != "java.sql.Timestamp") out.println "  @Excel(name=\"${it.comment}\")"
        out.println "  private ${it.type} ${it.name};\n"
    }
    out.println "}"
}



def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        def comment = "";
        if(col.getComment() != null) {
            comment = col.getComment()
            comment = new String(comment.getBytes("utf-8"),"gbk");
            new String()
        }
        fields += [[
                           isAuto: DasUtil.isAuto(col),
                            column: col,
                            columnName: col.getName(),
                           name : javaName(col.getName(), false),
                           type : typeStr,
                           comment: comment,
                           annos: ""]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/**
 * 查找指定目录现有的命名空间
 *
 * @param dir
 * @return
 */
def findPackageName(dir) {
    if(dir != null && dir.isDirectory()) {
        File[] files = dir.listFiles();
        if(files != null && files.length>0) {
            for (File item:files) {
                if(item.isFile()) {
                    List<String> lines = Files.readLines(item, StandardCharsets.UTF_8);
                    //查找命名空间
                    for (String line: lines) {
                        line = line.trim();
                        if(line.startsWith("package")) {
                            line = line.split(" ")[1];
                            line = line.replace(";", "")
                            line = line.trim();
                            return line;
                        }
                    }
                }
            }
        }
    }
    return ""
}